import { app, BrowserWindow, ipcMain, dialog, session, shell } from 'electron/main'
import * as chromeLauncher from 'chrome-launcher';
import * as puppeteer from 'puppeteer-core';
import * as playwright from 'playwright';
import fs from 'fs-extra';
import path from 'path';

const chromiumVersion = async () => {
    const userDataDir = app.getPath('userData');
    const sdkCachePath = path.join(userDataDir, 'sdk/cache/chromium');
    let versionDirs = []

    try {
        // 检查目录是否存在
        const exists = await new Promise((resolve) => {
            fs.exists(sdkCachePath, resolve);
        });

        if (!exists) {
            // console.error(`目录不存在: ${sdkCachePath}`);
            return versionDirs; // 如果目录不存在，直接返回空的 versionDirs
        }

        // 获取目录中的文件列表
        // const entries = await new Promise((resolve, reject) => {
        //     fs.readdir(sdkCachePath, { withFileTypes: true }, (err, entries) => {
        //         if (err) {
        //             reject(err);
        //         } else {
        //             resolve(entries);
        //         }
        //     });
        // });

        const entries = await fs.promises.readdir(sdkCachePath, {
            withFileTypes: true
        }).catch(err => {
            if (err.code === 'ENOENT') return [];
            throw err;
        });

        const isWindows = process.platform === 'win32';
        const isMac = process.platform === 'darwin';

        // 等待所有浏览器版本获取完成
        const promises = entries.map(async (entry) => {

            if (!entry.isDirectory()) return;

            const basePath = path.join(sdkCachePath, entry.name);
            let chromeExePath;

            // 跨平台路径处理
            if (isWindows) {
                chromeExePath = path.join(basePath, 'chrome-win', 'chrome.exe');
            } else if (isMac) {
                chromeExePath = path.join(
                    basePath,
                    'chrome-mac',
                    'Chromium.app',
                    'Contents',
                    'MacOS',
                    'Chromium'
                );
            } else {
                console.warn('Unsupported platform:', process.platform);
                return;
            }

            try {
                // 验证可执行文件存在
                await fs.promises.access(chromeExePath, fs.constants.X_OK);

                // 启动浏览器获取版本
                const browser = await puppeteer.launch({
                    executablePath: chromeExePath,
                    headless: true,  // 确保使用 headless 模式
                    args: ['--no-sandbox'] // macOS 可能需要
                }).catch(err => {
                    console.warn(`Failed to launch ${chromeExePath}:`, err.message);
                    return null;
                });

                if (!browser) return;

                try {
                    const version = await browser.version();
                    versionDirs.push({
                        version: version.match(/Chrome\/([\d.]+)/)?.[1] || 'unknown',
                        path: chromeExePath,
                        platform: process.platform
                    });
                } finally {
                    await browser.close().catch(() => { });
                }
            } catch (exeError) {
                console.warn(`Skipping invalid chromium: ${chromeExePath}`, exeError.message);
            }

            // if (entry.isDirectory()) {
            //     const chromeExePath = path.join(sdkCachePath, entry.name, 'chrome-win', 'chrome.exe');
            //     // console.log(chromeExePath);
            //     const browser = await puppeteer.launch({
            //         executablePath: chromeExePath
            //     });
            //     const version = await browser.version();  // 获取浏览器版本
            //     versionDirs.push({
            //         version: version,
            //         Path: chromeExePath
            //     })
            //     await browser.close();
            // }
        });

        // 等待所有异步操作完成
        await Promise.all(promises);

    } catch (err) {
        console.error(err);
    }

    // 返回最终的 versionDirs 对象
    return versionDirs;
};


export default chromiumVersion;